package com.zrrd.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.file.service.FileStorageService;
import com.zrrd.model.common.dtos.PageResponseResult;
import com.zrrd.model.common.dtos.ResponseResult;
import com.zrrd.model.common.enums.AppHttpCodeEnum;
import com.zrrd.model.wemedia.dtos.WmMaterialDto;
import com.zrrd.model.wemedia.pojos.WmMaterial;
import com.zrrd.utils.thread.WmThreadLocalUtil;
import com.zrrd.wemedia.mapper.WmMaterialMapper;
import com.zrrd.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.UUID;

/**
 * @author WanJl
 * @version 1.0
 * @title WmMaterialServiceImpl
 * @description
 * @create 2023/9/20 15:53
 */
@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1、检查一下参数是否存在
        if (multipartFile==null||multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2、把图片本身上传到MinIO中
        //给每一个上传的图片文件重新命名。
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId=null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName+postfix, multipartFile.getInputStream());
            log.info("上传成功，图片上传到MinIO中,fileId是：{}",fileId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl--上传图片失败");
        }

        //3、把图片Url存入数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //4、返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1、检查前端传过来的分页参数
        dto.checkParam();

        //2、分页查询
        IPage page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lqw=new LambdaQueryWrapper<>();
        //判断是否收藏
        if (dto.getIsCollection()==1){
            lqw.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //添加条件，要按照用户来查询
        lqw.eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId());

        //按照时间排序，倒序
        lqw.orderByDesc(WmMaterial::getCreatedTime);
        //-----以上，查询条件组合完成，开始分页查询


        //分页查询
        page = page(page, lqw);

        //返回结果
        //创建分页结果响应对象。将当前页数，每页条数，总条数作为参数返回。
        ResponseResult responseResult =
                new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        //添加返回的数据
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    /**
     * 收藏素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short)1);
        updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setId(id);
        wmMaterial.setIsCollection((short)0);
        updateById(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        boolean flag = removeById(id);
        return ResponseResult.okResult(flag);
    }

}
